import {createRouter, createWebHashHistory, NavigationGuardNext, RouteLocationNormalized} from "vue-router";
// 进度条动画
import NProgress from '../utils/animation'
import {UserPreferenceStore} from "@/utils/UserPreferenceStore.ts";

// 引入路由
export const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            meta: {title: '鑫盛源'},
            component: () => import('../views/index.vue')
        }
        ,
        {
            name: 'index',
            meta: {title: '首页'},
            path: '/main/index',
            component: () => import('../views/main/index.vue'),
        },
        {
            name: 'person',
            meta: {title: '个人基础信息'},
            path: '/base/info',
            component: () => import('../views/main/person/index.vue'),
        }
        ,
        {
            name: 'applyLoan',
            meta: {title: '申请贷款'},
            path: '/apply/applyLoan',
            component: () => import('../views/main/loan/index.vue'),
        }
        ,
        {
            name: 'car',
            meta: {title: '车源'},
            path: '/apply/car',
            component: () => import('../views/main/car/index.vue'),
        },
        {
            name: 'house',
            meta: {title: '房源'},
            path: '/apply/house',
            component: () => import('../views/main/house/index.vue'),
        },
        {
            name: 'succeed',
            meta: {title: '成功'},
            path: '/apply/succeed',
            component: () => import('../views/main/state/succeed.vue'),
        }
    ],

})

/** 路由白名单 */
const whiteList = ["/"];

/** 如果已经登录并存在登录信息后不能跳转到路由白名单，而是继续保持在当前页面 */
// function toRouter(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext, userInfo: string): void {
//     // whiteList.includes(to.fullPath) && userInfo ? next(from.fullPath) : next()
// }

router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    NProgress.start()

    // document.title = to.meta.title as string;
    const userInfo = UserPreferenceStore.getInstance().getToken();

    if (!userInfo) {
        // #未登录
        if (to.path !== '/') {
            // 未登录的情况下，判断白名单内是否有该路由，有则【直接进入】，否则跳转到登录页
            if (whiteList.includes(to.path)) {
                next()
            } else {
                next('/')
            }
        } else {
            next()
        }

    } else {
        // #已登录
        if (from) {

        }

        if (to.path === '/') {
            // 已登录的情况下，默认跳转到首页
            next('/main/index')
        } else {
            next()
        }
    }

})


router.afterEach(() => {
    // console.log(to);
    // console.log(from);
    NProgress.done()
})
